package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.CompanyService;
import com.xuanzheng.company.service.impl.CompanyServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet(urlPatterns = {"/getCurrentUser", "/api/user/current"})
public class GetCurrentUserServlet extends HttpServlet {
    private final CompanyService companyService = new CompanyServiceImpl();
    private final Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取当前用户
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("user");
            
            if (user == null) {
                result.put("success", false);
                result.put("message", "用户未登录");
            } else {
                Map<String, Object> userInfo = new HashMap<>();
                userInfo.put("id", user.getId());
                userInfo.put("name", user.getName());
                userInfo.put("role", user.getRole());
                userInfo.put("phone", user.getPhone());
                userInfo.put("email", user.getEmail());
                userInfo.put("gender", user.getGender());
                userInfo.put("age", user.getAge());
                userInfo.put("address", user.getAddress());
                userInfo.put("idCard", user.getIdCard());
                userInfo.put("status", user.getStatus());
                userInfo.put("employeeNumber", user.getEmployeeNumber());
                userInfo.put("companyId", user.getCompanyId());
                userInfo.put("position", user.getPosition()); // 添加职位信息
                
                // 如果是公司负责人，获取公司ID
                if (user.getRole() == 1) {
                    String companyId = user.getCompanyId();
                    if (companyId == null) {
                        // 尝试从数据库获取
                        companyId = companyService.getCompanyByManagerId(user.getId()) != null ? 
                                   companyService.getCompanyByManagerId(user.getId()).getId() : null;
                        
                        // 如果找到了公司ID，更新session中的用户信息
                        if (companyId != null) {
                            user.setCompanyId(companyId);
                            session.setAttribute("user", user);
                        }
                    }
                    userInfo.put("companyId", companyId);
                }
                
                // 添加公司负责人特有字段
                if (user.getRole() == 1) {
                    userInfo.put("companyName", user.getCompanyName());
                    userInfo.put("companyAddress", user.getCompanyAddress());
                    userInfo.put("companyPhone", user.getCompanyPhone());
                    userInfo.put("companyCreditCode", user.getCompanyCreditCode());
                }
                
                // 如果普通用户已加入公司，获取公司名称
                if (user.getRole() == 0 && user.getCompanyId() != null) {
                    // 尝试从User对象获取公司名称
                    String companyName = user.getCompanyName();
                    
                    // 如果User对象中没有公司名称，尝试从数据库获取
                    if (companyName == null || companyName.isEmpty()) {
                        companyName = companyService.getCompanyById(user.getCompanyId()) != null ?
                                     companyService.getCompanyById(user.getCompanyId()).getName() : "";
                    }
                    
                    userInfo.put("companyName", companyName);
                    
                    // 如果职位为空，尝试从数据库获取
                    if (user.getPosition() == null || user.getPosition().isEmpty()) {
                        // 从CompanyEmployeeDao获取职位信息
                        try {
                            com.xuanzheng.company.dao.CompanyEmployeeDao employeeDao = 
                                new com.xuanzheng.company.dao.impl.CompanyEmployeeDaoImpl();
                            com.xuanzheng.company.entity.CompanyEmployee employee = 
                                employeeDao.getCompanyEmployeeByUserIdAndCompanyId(user.getId(), user.getCompanyId());
                            if (employee != null && employee.getPosition() != null) {
                                userInfo.put("position", employee.getPosition());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                
                result.put("success", true);
                result.put("user", userInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "获取用户信息失败：" + e.getMessage());
        }
        
        out.write(gson.toJson(result));
        out.flush();
    }
} 